package cn.sgw.test.thread;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by sungaowei on 2017/09/28.
 */
public class CompletionService {

    private ExecutorService executorService;

    public CompletionService(ExecutorService executorService){
            this.executorService = executorService;
    }

    private void getResult(List<Integer> source){
        java.util.concurrent.CompletionService completionService = new ExecutorCompletionService<Integer>(executorService);

        source.forEach(s->{
            completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return s;
                }
            });
        });

        source.forEach(s->{
            try {
               Future<Integer> result = completionService.take();
                System.out.println(result.get());
                System.out.println(Thread.currentThread().getId());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
    }

    public static void main(String[] args) {
        CompletionService completionService = new CompletionService(Executors.newCachedThreadPool());
        List<Integer> list = Stream.of(1,2,3,4,5,6).collect(Collectors.toList());
        completionService.getResult(list);
    }

}
